<?php

namespace backend\controllers;

use backend\components\Qiniu;
use backend\models\EveryIsOk;
use backend\models\Goods;
use backend\models\GoodsCategory;
use backend\models\GoodsDayCount;
use backend\models\GoodsGallery;
use backend\models\GoodsIntro;
use backend\models\SearchForm;
use kucha\ueditor\UEditorAction;
use xj\uploadify\UploadAction;
use yii\data\Pagination;
use yii\db\Exception;
use yii\db\Query;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\helpers\VarDumper;
use yii\web\Controller;
use yii\web\Response;
use yii\web\UploadedFile;

class GoodsController extends Controller
{


    /**
     * 重新父类的行为 添加简单权限控制ACF(简单存取权限控制)
     * 添加行为控制过滤
     * @return array
     */
    public function behaviors()
    {
        return [
            'access'=>[
                'class'=>'backend\filter\AccessFilter',
            ],
            /*'acf'=>[
                'class'=>AccessControl::className(),
                'only'=>['index','list','add'], //表示之争对相应的操作添加存取控制
                'rules'=>[
                    //一个数组表示一条规则
                    [
                        //访问不允许的操作是会跳转到登录页面
                        'allow'=>true, //定义当前规则的类型 允许| 拒绝
                        'actions'=>['list'],//定义当前能够访问的操作
                        'roles'=>['employee'],//设置当前规则的作用的对象('?' 游客 未登录用户)
                    ],
                    [
                        'allow'=>true,
                        'actions'=>['add'],
                        'roles'=>['@'],
                    ],
                    [
                        //'allow'=>true,

                    ],
                ]
            ]*/
        ];
    }




    public function actionInit(){
        $auth = \Yii::$app->authManager;
        //添加权限
        $addgoods = $auth->createPermission('addgoods');
        $addgoods->description ='add goods' ;
        $auth->add($addgoods);

    }
    /*
 * 进度条
 */
    public function actions() {
        return [
            'upload' => [
//                'class' => 'kucha\ueditor\UEditorAction',
                'class' => UEditorAction::className(),
            ],
            's-upload' => [
                'class' => UploadAction::className(),
                'basePath' => '@webroot/uploads',
                'baseUrl' => '@web/uploads',
                'enableCsrf' => true, // default
                'postFieldName' => 'Filedata', // default
                //BEGIN METHOD
                //'format' => [$this, 'methodName'],
                //END METHOD
                //BEGIN CLOSURE BY-HASH
                'overwriteIfExist' => true,
                /*'format' => function (UploadAction $action) {
                    $fileext = $action->uploadfile->getExtension();
                    $filename = sha1_file($action->uploadfile->tempName);
                    return "{$filename}.{$fileext}";
                },*/
                //END CLOSURE BY-HASH
                //BEGIN CLOSURE BY TIME
                'format' => function (UploadAction $action) {
                    $fileext = $action->uploadfile->getExtension();
                    $filehash = sha1(uniqid() . time());
                    $p1 = substr($filehash, 0, 2);
                    $p2 = substr($filehash, 2, 2);
                    return "{$p1}/{$p2}/{$filehash}.{$fileext}";
                },
                //END CLOSURE BY TIME
                'validateOptions' => [
                    'extensions' => ['jpg', 'png'],
                    'maxSize' => 1 * 1024 * 1024, //file size
                ],
                'beforeValidate' => function (UploadAction $action) {
                    //throw new Exception('test error');
                },
                'afterValidate' => function (UploadAction $action) {},
                'beforeSave' => function (UploadAction $action) {},
                'afterSave' => function (UploadAction $action) {
                    $action->output['fileUrl'] = $action->getWebUrl();
                    $action->getFilename(); // "image/yyyymmddtimerand.jpg"
                    $action->getWebUrl(); //  "baseUrl + filename, /upload/image/yyyymmddtimerand.jpg"
                    $action->getSavePath(); // "/var/www/htdocs/upload/image/yyyymmddtimerand.jpg"
                },
            ],
            ''=>[

            ],
        ];
    }


    /*
     * 实现列表也的搜索功能 ajax
     */
    public function actionSearchTitle ($q)
    {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $out = ['results' => ['id' => '', 'text' => '']];
        if (!$q) {
            return $out;
        }
        try{
            $data = Goods::find()
                ->select('id, name as text,sn')
                ->andFilterWhere(['like', 'name', $q])
                ->orFilterWhere(['like', 'sn', $q])
                ->limit(50)
                ->asArray()
                ->all();

            $out['results'] = array_values($data);

            return $out;
        }catch (Exception $exception){
            var_dump($exception);
            exit;
        }



    }


    /*
     * 展示商品的首页
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /*
     * 实现显示商品的列表
     */
    public function actionList(){
        //实例化表单模型
        $search = new SearchForm();

        $query = Goods::find();
        //调用方法搜索
        $search->search($query);
        //实例化分页工具条
        $pager =EveryIsOk::getPager($query);
        //获取当前页码的数据
        $models = $query->limit($pager->limit)->offset($pager->offset)->all();

        Url::remember(Url::current(),'goodslist');
        //显示视图
        return $this->render('list',[
            'models'=>$models,
            'pager'=>$pager,
            'search'=>$search,
        ]);
    }


    /*
     * 实现商品的添加
     */
    public function actionAdd()
    {
        //实例化表单模型
        $model = new Goods();
        $goodsIntro = new GoodsIntro();
        //实例化请求
        $request = \Yii::$app->request;
        //判断请求方式并且加载数据//验证数据
        if($request->isPost && $model->load($request->post()) && $goodsIntro->load($request->post())){
            //调用组件吧图片上传到七牛云
            $qiniu = \Yii::$app->get('qiniu');
            //获取图片的绝对路径
            $path = \Yii::getAlias('@webroot').$model->logo;
            //上传图片
            $qiniu->uploadFile($path,$model->logo);
            //获取上传的图片的路径
            $link = $qiniu->getLink($model->logo);
            $model->logo = $link;
            //调用方法生成货号
            $model->createSn();
            //验证数据//保存商品的数据
            if($model->validate() && $goodsIntro->validate() && $model->save()){
                //得到商品的id
                $goodsIntro->goods_id = $model->id;
                //保存商品详情
                if($goodsIntro->save()){
                    //保存成功后跳转到商品相册添加页面

                    \Yii::$app->session->setFlash('success','商品添加成功!');

                    return $this->redirect(['goods/add-gallery','goods_id'=>$model->id]);
                }
            }
        }
        //显示视图
        return $this->render('add',[
            'model'=>$model,
            'goodsIntro'=>$goodsIntro,
        ]);
    }

    /*
     * 实现商品的相册的添加 (商品相册的展示)
     */
    public function actionAddGallery($goods_id=''){
        //实例化表单模型
        $model = new GoodsGallery();
        //实例化请求
        $request = \Yii::$app->request;
                if($request->isPost){
                    /*//得到上传的信息
                    $model->uploadAlbum=UploadedFile::getInstances($model,'uploadAlbum');
                    //循环

                    foreach($model->uploadAlbum as $key=>$img){
                        $gallery = $model;
                        //$gallery =new GoodsGallery();
                        //得到商品的id
                        $gallery->goods_id = $goods_id;
                        $filename = 'uploads/goods/logo'.uniqid()."$key".$img->extension;
                        //保存图片
                        $img->saveAs($filename,false);
                        //保存信息
                        $gallery->path = '/'.$filename;
                        $gallery->save();
                    }*/

                    //保存成功后跳转到列表页面
                    \Yii::$app->session->setFlash('success','添加相册成功');

                    return $this->redirect(['goods/list']);
                }

        //实例化获得需要添加相册的表单模型
        //$goods = Goods::findOne(['id'=>$goods_id]);
        //显示添加页面
        //return $this->render('newAlbum',['model'=>$model,'goods'=>$goods]);


        // 假设商品的banner图是 $relationBanners的集合, $id是商品的id
// $relationBanners的数据结构如：
        /**
         * Array
         *(
         *   [0] => Array
         *        (
         *            [id] => 1484314
         *            [goods_id] => 1173376
         *            [banner] => ./uploads/20160617/146612713857635322241f2.png
         *        )
         *
         *)
         */

        $relationGoodsCallery = GoodsGallery::find()->where(['goods_id' => $goods_id])->asArray()->all();

        // @param $p1 Array 需要预览的商品图，是商品图的一个集合
        // @param $p2 Array 对应商品图的操作属性，我们这里包括商品图删除的地址和商品图的id
        $p1 = $p2 = [];
        if ($relationGoodsCallery) {
            foreach ($relationGoodsCallery as $k => $v) {
                //var_dump($v);exit;
                $p1[$k] = $v['path'];
                $p2[$k] = [
                    // 要删除商品图的地址
                    'url' => Url::toRoute('/goods/del-album'),
                    // 商品图对应的商品图id
                    'key' => $v['id'],
                ];
            }
        }

        return $this->render('newAlbum', [
            // other params
            'p1' => $p1,
            'p2' => $p2,
            // 商品id
            'id' => $goods_id,
            'model'=>$model,
        ]);
    }

    /**
     * 实现商品相册的删除
     * @return array
     */
    public function actionDelAlbum(){
        // 前面我们已经为成功上传的banner图指定了key,此处的key也即时banner图的id
        $rs ='';
        if ($id = \Yii::$app->request->post('key')) {
            $model = GoodsGallery::findOne(['id'=>$id]);

            $rs = $model?$model->delete():'相片已经删除';


        }
        \Yii::$app->response->format = Response::FORMAT_JSON;
        return ['success' => true,'data'=>$rs];
    }
    /*
     * 更新商品的相册
     */
    public function actionAsyncBanner ()
    {
        // 商品ID  Goods_id ==29
        $id = \Yii::$app->request->post('goods_id');

        // $p1 $p2是我们处理完图片之后需要返回的信息，其参数意义可参考上面的讲解
        $p1 = $p2 = [];


        // 如果没有商品图或者商品id非真，返回空
        if (empty($_FILES['GoodsGallery']['name']) || empty($_FILES['GoodsGallery']['name']['uploadAlbum']) || !$id) {
            echo '{}';
            return;
        }

        // 循环多张商品goodsGallery图进行上传和上传后的处理
        $qiniu = \Yii::$app->get('qiniu');


        for ($i = 0; $i < count($_FILES['GoodsGallery']['name']['uploadAlbum']); $i++) {
            // 上传之后的商品图是可以进行删除操作的，我们为每一个商品成功的商品图指定删除操作的地址
            $url = Url::to(['goods/del-album']);

            // 调用图片接口上传后返回的图片地址，注意是可访问到的图片地址哦
            //$imageUrl = '';

                $gallery = new GoodsGallery();
                //得到上传的信息
                $gallery->uploadAlbum=UploadedFile::getInstances($gallery,'uploadAlbum')[0];
                //得到商品的id
                $gallery->goods_id = $id;
                //var_dump($gallery);exit;
                $filename = 'uploads/goods/album' . uniqid() . "$i.". $gallery->uploadAlbum->extension;
                //保存图片
                $gallery->uploadAlbum->saveAs($filename, false);
                //保存信息
                $imageUrl ='/' . $filename;
               // $gallery->path =$imageUrl;

                $key = 0;
                //获取相册图片的绝对路径
                $absolutePath = \Yii::getAlias('@webroot').$imageUrl;

                $qiniu->uploadFile($absolutePath,$imageUrl);

                $link = $qiniu->getlink($imageUrl);

                $gallery->path = $link;
                $imageUrl = $link;


                if ($gallery->save(false)) {
                    $key = $gallery->id;
                }

                // 这是一些额外的其他信息，如果你需要的话
                // $pathinfo = pathinfo($imageUrl);
                // $caption = $pathinfo['basename'];
                // $size = $_FILES['Banner']['size']['banner_url'][$i];


                $p1[$i] = $imageUrl;
                $p2[$i] = ['url' => $url, 'key' => $key];
        }


        // 返回上传成功后的商品图信息
        echo json_encode([
            'initialPreview' => $p1,
            'initialPreviewConfig' => $p2,
            'append' => true,
        ]);
        return;
    }

    /*
     * 删除所有的album
     */
    public function actionDeleAllAlbum($goods_id){
        var_dump($goods_id);
    }
    /*
     * 商品的编辑
     */
    public function actionEdit($id)
    {
        //实例化表单模型
        $model = Goods::findOne(['id'=>$id]);
        $goodsIntro = GoodsIntro::findOne(['goods_id'=>$id])?GoodsIntro::findOne(['goods_id'=>$id]):new GoodsIntro();
        $goodsIntro->goods_id = $model->id;
        //实例化请求
        $request = \Yii::$app->request;
        //判断请求方式并且加载数据//验证数据
        if($request->isPost && $model->load($request->post()) && $goodsIntro->load($request->post())){
            //调用组件吧图片上传到七牛云
            $qiniu = \Yii::$app->get('qiniu');
            //获取图片的绝对路径
            $path = \Yii::getAlias('@webroot').$model->logo;
            //上传图片
            $qiniu->uploadFile($path,$model->logo);
            //获取上传的图片的路径
            $link = $qiniu->getLink($model->logo);
            $model->logo = $link;
            //调用方法生成货号
            $model->createSn();
            //验证数据//保存商品的数据
            if($model->validate() && $goodsIntro->validate() && $model->save()){
                //得到商品的id
                $goodsIntro->goods_id = $model->id;
                //保存商品详情
                if($goodsIntro->save()){
                    //保存成功后跳转到商品相册添加页面

                    \Yii::$app->session->setFlash('success','商品添加成功!');

                    return $this->redirect(['goods/add-gallery','goods_id'=>$model->id]);
                }
            }
        }
        //显示视图
        return $this->render('add',[
            'model'=>$model,
            'goodsIntro'=>$goodsIntro,
        ]);
    }

    /*
     * 编辑相册
     */
   /* public function actionEditGallery($goods_id){

        //实例化表单模型
        $model = new GoodsGallery();
        //实例化请求
        $request = \Yii::$app->request;
        if($request->isPost){
            //得到上传的信息
            $model->uploadAlbum=UploadedFile::getInstances($model,'uploadAlbum');
            //循环
            foreach($model->uploadAlbum as $key=>$img){
                $gallery = new GoodsGallery();
                //得到商品的id
                $gallery->goods_id = $goods_id;
                $filename = 'uploads/goods/logo'.uniqid()."$key".$img->extension;
                //保存图片
                $img->saveAs($filename,false);
                //保存信息
                $gallery->path = $filename;
                $gallery->save();
            }

            //保存成功后跳转到列表页面
            \Yii::$app->session->setFlash('success','添加相册成功');

            return $this->redirect(['goods/list']);
        }

        //实例化获得需要添加相册的表单模型
        $goods = Goods::findOne(['id'=>$goods_id]);
        //显示添加页面
        return $this->render('newAlbum',['model'=>$model,'goods'=>$goods]);
    }*/

    /*
     * 商品的展示
     */
    public function actionShow($id)
    {
        //实例化表单模型
        $model = Goods::findOne(['id'=>$id]);
        $goodsIntro = GoodsIntro::findOne(['goods_id'=>$model->id]);
        $goodsGallery = GoodsGallery::findAll(['goods_id'=>$id]);
        //显示视图
        return $this->render('show',[
            'model'=>$model,
            'goodsIntro'=>$goodsIntro,
            'goodsGallerys'=>$goodsGallery,
        ]);
    }


    /*
     * 实现商品的逻辑删除
     */
    public function actionDel($id){
        //把对应的数据中的状态值更新为-1
        $rs = \Yii::$app->db->createCommand()->update('goods',['status'=>0],['id'=>$id])->execute();
        //执行成功后提示用户并且,跳转到列表页
        if($rs){
            \Yii::$app->session->setFlash('success','删除成功!');
        }else{
            \Yii::$app->session->setFlash('success','删除失败!');
        }

        return $this->redirect(['goods/list']);
    }

    /*
     * 显示商品的回收站
     */
    public function actionRecycleBin(){
        //获取所有的删除的数据
        $query = Goods::find()->where(['=','status',0]);
        //得到总的数据的条数
        $totalCount = $query->count();
        //得到分页中每页的条数
        $pagesize = 3;
        //实例化分页工具条
        $pager = new Pagination([
            'totalCount'=>$totalCount,
            'pageSize'=>$pagesize,
        ]);
        //获取当前页码的数据
        $model = $query->limit($pager->limit)->offset($pager->offset)->all();
        //显示视图
        return $this->render('recycleBin',['models'=>$model,'pager'=>$pager]);
    }

    /*
     * 恢复逻辑删除的商品
     */
    public function actionRecovery($id)
    {
        //把对应的数据中的状态值更新为1
        $rs = \Yii::$app->db->createCommand()->update('goods',['status'=>1],['id'=>$id])->execute();
        //执行成功后提示用户并且,跳转到列表页
        if($rs){
            \Yii::$app->session->setFlash('success','恢复成功!');
        }else{
            \Yii::$app->session->setFlash('success','恢复失败!');
        }

        return $this->redirect(['goods/list']);
    }


    /*
   * 实现商品的彻底删除
   */
    public function actionDelete($id){
        $rs = \Yii::$app->db->createCommand()->delete('goods',['id'=>$id])->execute();

        if($rs){
            \Yii::$app->session->setFlash('success','彻底删除成功!');
        }else{
            \Yii::$app->session->setFlash('success','彻底删除失败!');
        }

        return $this->redirect(['goods/recycle-bin']);

    }

}
